//
//  SLStatusViewModel.swift
//  0319iOSweiboDemo
//
//  Created by Tang on 16/3/25.
//  Copyright © 2016年 大天朝. All rights reserved.
//

import UIKit
import SDWebImage

class SLStatusViewModel: NSObject {
    //单例
    static let sharedInstance: SLStatusViewModel = SLStatusViewModel()
    
    //1.是否在加载微博数据
    private var loading: Bool = false
    
    /// 加载微博数据
    func loadStatus(since_id: Int64, max_id: Int64, loadStatusCallback: (statuses: [SLStatus]?, error: NSError?) -> ()) {
        //2.判断有人是否在加载数据
        if loading {
            SLPrint(msg: "有人正在加载微博数据")
            //告诉调用的人.有人正在微博数据
            //domain: 域.自定义.主要表示错误范围
            //code: 自定义/
//            let repreatRefresh = SLNetworkToolError.RepeatRefresh
//            let error = NSError(domain: "error.net.status", code: repreatRefresh.rawValue, userInfo: ["errorDescription" : repreatRefresh.errorDescription])
//            loadStatusCallback(statuses: nil, error: error)
            loadStatusCallback(statuses: nil, error: SLNetworkToolError.RepeatRefresh.error())
            return
        }
        
        //3.之前有人加载微博数据
        loading = true
        //https://api.weibo.com/2/statuses/home_timeline.json
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"

//        var parametes: [String: AnyObject] = ["access_token": SLUserAccountViewModel.sharedInstance.userAccount!.access_token!]
        //请求参数  封装之后
        var parametes = [String: AnyObject]()

        //需要下拉刷新.返回比since_id大的微博
        if since_id > 0 {
            parametes["since_id"] = NSNumber(longLong: since_id)
        } else if max_id > 0 {
            //上拉刷新
            parametes["max_id"] = NSNumber(longLong: max_id - 1)
        }
    
        
//        parametes["count"] = 2 //指定加载2条
        SLNetworkTool.sharedInstance.AFNManager.GET(urlString, parameters: parametes, progress: nil, success: { (_, result) -> Void in
//            SLPrint(msg: "数据加载完成: \(result)")
            }) { (_, error) -> Void in
                SLPrint(msg: "数据加载失败: \(error)")
        }
        SLNetworkTool.sharedInstance.requestGET(urlString, parameters: parametes) { (result, error) -> () in
            
            //4.微博数据加载完成.将liading改为false.以便可以再次使用
            self.loading = false
            if error != nil {
//                SLPrint(msg: "请求微博数据出现错误: \(error)")
                loadStatusCallback(statuses: nil, error: error)
                return
            }
//            SLPrint(msg: "请求微博数据出现成功: \(result)")
            //[[String: AnyObject]] 数组里面存的是字典类型的元素
            let statusesArray = result?["statuses"] as? [[String: AnyObject]]
            
            //定义空数组存放微博模型
            var statuses = [SLStatus]()
            
            //遍历微博数组
            for dict in statusesArray! {
                //字典转模型
               let status = SLStatus(dict: dict)
                statuses.append(status)
            }
            
            
            //当字典转模型完成后.来缓存微博模型里的图片.当微博里面的图片缓存完成了.才通知控制器来显示
            self.cacheWebImahge(statuses, loadStatusCallback: loadStatusCallback)
            
            //字典转模型完成了
//            SLPrint(msg: "字典转模型完成了: \(statuses)")
            //当转模型完成了.通知控制器来显示微博数据
//            loadStatusCallback(statuses: statuses, error: nil)
        }
    }
    //缓存微博图片
    private func cacheWebImahge(statuses: [SLStatus], loadStatusCallback: (statuses: [SLStatus]?, error: NSError?) -> ()) {
        //创建group
        let group = dispatch_group_create()
        
        var length: CGFloat = 0
        //查找微博里面的图片.下载下来
        for status in statuses {
            var downloadURLs = status.storePictureURLs
            if downloadURLs == nil {
                //如果原创没有.找转发的微博
                downloadURLs = status.retweeted_status?.storePictureURLs
            }
            if downloadURLs == nil {
                continue
            }
            if downloadURLs?.count == 1 {
                let url = downloadURLs![0]
                // 在异步任务之前进入组
                dispatch_group_enter(group)
//            for url in downloadURLs! {
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options:SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in // SDWebImage下载完成图片的时候的回调
                    // 不管是下载成功还是失败,任务都完成了.就需要离开组
                        dispatch_group_leave(group)
                        if error != nil {
                            SLPrint(msg: "SDWebImageManager下载图片失败: \(url)")
                            return
                        }
//                        SLPrint(msg: "下载图片成功: \(url)")
                        let data = UIImagePNGRepresentation(image)!
                        length += CGFloat(data.length)
                })
            }
        
        }
        // 所有模型的图片都下载完成才通知我
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            let len = length / 1024 / 1024.0
            let l = String(format: "%0.2f", arguments: [len])
//            SLPrint(msg: "所有图片都缓存完成: \(l) MB")
            
            // 所有图片都缓存完成,通知控制器来显示微博数据
           loadStatusCallback(statuses: statuses, error: nil) 
        }
    }
    
    /**
     发布微博,续两次发布的微博不可以重复
     
     - parameter status:             微博的文本内容
     - parameter sendStatusCallback: 发布微博的回调
     */
    func sendStatus(status: String, senStatusCallBark: (error: NSError?) -> ()) {
        guard let access_token = SLUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            senStatusCallBark(error: SLNetworkToolError.EmptyAccessToken.error())
            return
        }
    
         // url
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let parameters = [
            "access_token" : access_token,
            "status" : status
        ]
        
        SLNetworkTool.sharedInstance.requestPOST(urlString, parameters: parameters) { (result, error) -> () in
            if error != nil {
                senStatusCallBark(error: error)
                return
            }
            
            //发布微博成功了
            senStatusCallBark(error: nil)
        }
    }
}
